﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        private readonly Manager.BLL.Admin.M_ProductBll bll = new Manager.BLL.Admin.M_ProductBll();
        //
        // GET: /Admin/Product/
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet, Ope = "view")]
        public ActionResult Index()
        {
            Manager.BLL.Admin.M_ShopBll shopBll=new Manager.BLL.Admin.M_ShopBll();
            Manager.BLL.Admin.M_CategoryBll categoryBll=new Manager.BLL.Admin.M_CategoryBll();

            var query = from p in bll.GetModelList(string.Empty)
                        select new Models.Product
                        {
                            ProductID = p.ProductID,
                            ProductName = p.ProductName,
                            ProductShopName = p.ProductShopID.HasValue?shopBll.GetModel(p.ProductShopID.Value).ShopName:"无",
                            ProductTypeName = categoryBll.GetModel(p.ProductTypeID.Value).TypeName,
                            IsTop = p.IsTop ? "是" : "否",
                            IsValid = p.IsValid ? "是" : "否"
                        };
            return View(query.ToList<Models.Product>());
        }

        [HttpPost]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet, Ope = "view")]
        public ActionResult Index(FormCollection forms)
        {
            try
            {
                Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();
                Manager.BLL.Admin.M_ShopBll shopBll = new Manager.BLL.Admin.M_ShopBll();

                string StylistID = forms["tbxSearchProductID"];
                string StylistName = forms["tbxSearchProductName"];
                string StylistShopName = forms["tbxSearchProductShopName"];
                string StylistTypeName = forms["tbxSearchProductTypeName"];
                string StylistIsTop = forms["tbxSearchIsTop"];
                string StylistIsValid = forms["tbxSearchIsValid"];

                var query = from p in bll.GetModelList("")
                            select new Models.Product
                            {
                                ProductID = p.ProductID,
                                ProductName = p.ProductName,
                                ProductShopName = shopBll.GetModel(p.ProductShopID.Value).ShopName,
                                ProductTypeName = categoryBll.GetModel(p.ProductTypeID.Value).TypeName,
                                IsTop = p.IsTop ? "是" : "否",
                                IsValid = p.IsValid ? "是" : "否"
                            };
                if (StylistID.Length > 0)
                    query = query.Where(p => p.ProductID == int.Parse(StylistID));
                if (StylistName.Length > 0)
                    query = query.Where(p => p.ProductName.Contains(StylistName));
                if (StylistShopName.Length > 0)
                    query = query.Where(p => p.ProductShopName.Contains(StylistShopName));
                if (StylistTypeName.Length > 0)
                    query = query.Where(p => p.ProductTypeName.Contains(StylistTypeName));
                if (StylistIsTop.Length > 0)
                    query = query.Where(p => p.IsTop.Equals(StylistIsTop));
                if (StylistIsValid.Length > 0)
                    query = query.Where(p => p.IsValid.Equals(StylistIsValid));

                return View(query.ToList<Models.Product>());
            }
            catch
            {
                Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();
                Manager.BLL.Admin.M_ShopBll shopBll = new Manager.BLL.Admin.M_ShopBll();

                var query = from p in bll.GetModelList(string.Empty)
                            select new Models.Product
                            {
                                ProductID = p.ProductID,
                                ProductName = p.ProductName,
                                ProductShopName = shopBll.GetModel(p.ProductShopID.Value).ShopName,
                                ProductTypeName = categoryBll.GetModel(p.ProductTypeID.Value).TypeName,
                                IsTop = p.IsTop ? "是" : "否",
                                IsValid = p.IsValid ? "是" : "否"
                            };
                return View(query.ToList<Models.Product>());
            }
        }

        /// <summary>
        /// 门店类别下拉列表框
        /// </summary>
        public void BindSelect()
        {
            Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();
            IEnumerable<SelectListItem> categorys = from c in categoryBll.GetModelList("ModuleID=" + (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet) select new SelectListItem { Value = c.TypeID.ToString(), Text = c.TypeName };
            ViewBag.CategorySelect = categorys;

            Manager.BLL.Admin.M_ShopBll shopBll = new Manager.BLL.Admin.M_ShopBll();
            List<SelectListItem> res = new List<SelectListItem>();
            res.Add(new SelectListItem { Text="--请选择--",Value=""});
            IEnumerable<SelectListItem> shops = from s in shopBll.GetModelList("IsValid=1") select new SelectListItem { Value = s.ShopID.ToString(), Text = s.ShopName };
            res.AddRange(shops);
            ViewBag.ShopSelect = res;
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet, Ope = "add")]
        public ActionResult Add()
        {
            BindSelect();
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet, Ope = "add")]
        public ActionResult Add(Manager.Model.Admin.M_Product model, FormCollection forms)
        {
            Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();
            Manager.BLL.Admin.M_ShopBll shopBll = new Manager.BLL.Admin.M_ShopBll();

            try
            {
                if (!categoryBll.Exists(model.ProductTypeID.Value))
                    ModelState.AddModelError("", Resources.Global.msg_select_exist);
                /*
                if (!shopBll.Exists(model.ProductShopID.Value))
                    ModelState.AddModelError("", Resources.Global.msg_select_exist);
                */
                //上传
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase fileImage = Request.Files[0];
                    if (fileImage.FileName.Length != 0)
                    {
                        string urlImage = (new Manager.Tools.FileUpload()).SaveFile(fileImage, "Product");
                        if (urlImage.IndexOf("/") == -1)
                        {
                            ModelState.AddModelError("ProductImage", urlImage);
                        }
                        else
                        {
                            model.ProductImage = urlImage;
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    int r = bll.Add(model);
                    if (r > 0)
                        return RedirectToAction("Index", "Product");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            BindSelect();
            return View(model);
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet, Ope = "edit")]
        public ActionResult Edit(int id)
        {
            BindSelect();
            if (!bll.Exists(id))
                return RedirectToAction("Index");
            return View(bll.GetModel(id));
        }

        [HttpPost]
        [ValidateInput(false)]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet, Ope = "edit")]
        public ActionResult Edit(int id, Manager.Model.Admin.M_Product model, FormCollection forms)
        {
            Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();
            Manager.BLL.Admin.M_ShopBll shopBll = new Manager.BLL.Admin.M_ShopBll();

            model.ProductID = id;
            if (!bll.Exists(id))
                ModelState.AddModelError("", Resources.Global.msg_select_exist);
            else
                model.ProductImage = bll.GetModel(id).ProductImage;
            try
            {
                //上传
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase fileImage = Request.Files[0];
                    if (fileImage.FileName.Length != 0)
                    {
                        bool res = (new Manager.Tools.FileUpload()).DeleteExistFile(Server.MapPath("~" + model.ProductImage));
                        string urlImage = (new Manager.Tools.FileUpload()).SaveFile(fileImage, "Product");
                        if (urlImage.IndexOf("/") == -1)
                        {
                            ModelState.AddModelError("ProductImage", urlImage);
                        }
                        else
                        {
                            model.ProductImage = urlImage;
                        }
                    }
                }
                //表单保存
                if (ModelState.IsValid)
                {
                    if (!categoryBll.Exists(model.ProductTypeID.Value))
                        ModelState.AddModelError("", Resources.Global.msg_select_exist);
                    if (!shopBll.Exists(model.ProductShopID.Value))
                        ModelState.AddModelError("", Resources.Global.msg_select_exist);
                    model.ProductDesc = forms["ShopDesc"];
                    bool r = bll.Update(model);
                    if (r)
                        return RedirectToAction("Index", "Product");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            BindSelect();
            return View(model);
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ProductSet, Ope = "del")]
        public ActionResult Del(int id)
        {
            if (!bll.Exists(id))
                return Content("<script>alert('" + Resources.Global.msg_select_exist + "');location.href='/Admin/Product/Index';</script>");

            try
            {
                bool r = bll.Delete(id);
                if (r)
                    return Content("<script>alert('" + Resources.Global.msg_success + "');location.href='/Admin/Product/Index';</script>");
                else
                    return Content("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/Product/Index';</script>");

            }
            catch (Exception)
            {
                return JavaScript("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/Product/Index';</script>");
            }
        }
    }
}
